package org.niugang.coding.conf;

import com.alibaba.fastjson.JSON;
import org.niugang.coding.exception.CustomException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义无权限异常
 * Created by niugang on 2019/01/24.
 */
@Component
public class AuthenticationAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse resp,
                       AccessDeniedException e) throws IOException {
        resp.setStatus(HttpStatus.FORBIDDEN.value());
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        CustomException respBean = CustomException.builder().message("权限不足，请联系管理员").status(HttpStatus.UNAUTHORIZED.value()).path(request.getRequestURL().toString()).timestamp(System.currentTimeMillis()).build();
        out.write(JSON.toJSONString(respBean));
        out.flush();
        out.close();
    }
}
